package com.fansl.koala.quickdev.component;

import com.alibaba.fastjson.JSONObject;
import com.fansl.koala.quickdev.common.bean.R;
import com.fansl.koala.quickdev.common.enums.ResultEnum;
import com.fansl.koala.quickdev.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fansl
 * @Description: TODO
 * @date 2020/3/12 14:08
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(BizException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public R handleCustomException(BizException e) {
        log.info("desc:{},info:{}", "统一异常捕获[自定义异常]",
                JSONObject.toJSONString(new Object[]{e.getCode(), e.getMessage()}));
        return R.builder()
                .code(e.getCode())
                .message(e.getMessage())
                .build();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleException(Exception e) {
        log.error("desc:{}", "统一异常捕获[未知异常]", e);
        return R.failed(ResultEnum.SERVER_ERROR.getMessage());
    }

    /**
     * 判断是否是Ajax请求
     *
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null &&
                "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

}
